const path = require('path');
const { DefinePlugin } = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const { merge } = require('webpack-merge');
const devcfg = require('./webpack.dev');
const procfg = require('./webpack.pro');

//1:用来测试每个loader,plugin打包时间
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();

//2:

const commoncfg = {
  entry: './src/js/index.js',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name]_[contenthash:6].js',
    chunkFilename: 'chunk_[contenthash:6].js',
  },
  module: {
    rules: [
      {
        test: /\.js$/i,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
      {
        test: /\.vue$/i,
        exclude: /node_modules/,
        use: ['vue-loader'],
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg)$/, // 处理图片文件
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024,
              name: '[name].[ext]',
            },
          },
        ],
      },
    ],
  },
  resolveLoader: {
    modules: ['node_modules'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
    new CopyPlugin({
      patterns: [
        {
          from: './public',
          globOptions: {
            ignore: ['**/.DS_Store', '**/index.html'],
          },
        },
      ],
    }),
    new DefinePlugin({
      BASE_URL: '"./"',
    }),
    new VueLoaderPlugin(),
  ],
};

module.exports = function (env) {
  const cfg = env.production ? procfg : devcfg;
  // return smp.wrap(merge(commoncfg, cfg));
  return merge(commoncfg, cfg);
};
